package com.github.gaojh.server.http;

import com.github.gaojh.server.utils.JsonTools;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gaojh
 * @since 2020/3/23
 */
@Slf4j
public class Response implements HttpResponse {
    private Map<String, String> headers = new ConcurrentHashMap<>();
    private File file;
    private InputStream inputStream;
    private boolean isDownload = false;
    private String fileName;
    /**
     * 接受HttpResponse.sendJson()
     */
    private String json = null;

    /**
     * 接受HttpResponse.sendHtml()
     */
    private String html = null;

    @Override
    public void addHeader(String key, String value) {
        this.headers.put(key, value);
    }

    @Override
    public void setDownloadFile(File file) {
        this.file = file;
        this.isDownload = true;
        this.fileName = file.getName();
    }

    @Override
    public void setDownloadFile(InputStream inputStream, String fileName) {
        this.inputStream = inputStream;
        this.isDownload = true;
        this.fileName = fileName;
    }

    @Override
    public void sendJson(Object object) {
        this.json = JsonTools.DEFAULT.toJson(object);
        headers.put("content-type", "application/json;charset=UTF-8");
    }

    @Override
    public void sendHtml(String html) {
        this.html = html;
        headers.put("content-type", "text/html;charset=UTF-8");
    }

    @Override
    public void redirect(String url) {
        headers.put("location", url);
    }

    @Override
    public Map<String, String> getHeaders() {
        return headers;
    }

    @Override
    public File getFile() {
        return file;
    }

    @Override
    public InputStream getInputStream() {
        return inputStream;
    }

    @Override
    public boolean isDownload() {
        return isDownload;
    }

    @Override
    public String getFileName() {
        return fileName;
    }

    @Override
    public String getJson() {
        return json;
    }

    @Override
    public String getHtml() {
        return html;
    }

}
